<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>builder pattern建造者模式</title>
</head>
<body>
</body>
<script type="text/javascript">
    /**
     * 商店：Director指挥者类
     * @constructor
     */
    function Shop() {
        this.construct = function (builder) {
            builder.step1();
            builder.step2();
            return builder.get();
        }
    }

    /**
     * 汽车制造商：建造者类
     * @constructor
     */
    function CarBuilder() {
        this.car = null;

        this.step1 = function () {
            this.car = new Car();
        };

        this.step2 = function () {
            this.car.addParts();
        };

        this.get = function () {
            return this.car;
        };
    }

    /***
     * 卡车制造商：建造者类
     * @constructor
     */
    function TruckBuilder() {
        this.truck = null;

        this.step1 = function () {
            this.truck = new Truck();
        };

        this.step2 = function () {
            this.truck.addParts();
        };

        this.get = function () {
            return this.truck;
        };
    }

    /**
     * 产品类：car
     * @constructor
     */
    function Car() {
        this.doors = 0;

        this.addParts = function () {
            this.doors = 4;
        };

        this.say = function () {
            log.add("我是一辆" + this.doors + "门汽车");
        };
    }

    /**
     * 产品类：Truck
     * @constructor
     */
    function Truck() {
        this.doors = 0;

        this.addParts = function () {
            this.doors = 2;
        };

        this.say = function () {
            log.add("我是一辆" + this.doors + "门卡车");
        };
    }


    // 日志打印
    var log = (function () {
        var log = "";
        return {
            add: function (msg) {
                log += msg + "\n";
            },
            show: function () {
                alert(log);
                log = "";
            }
        }
    })();

    //运行程序
    function run() {
        var shop = new Shop();
        var carBuilder = new CarBuilder();
        var truckBuilder = new TruckBuilder();
        //客户通过向商店提供不同的汽车构建器，得到不同的汽车
        var car = shop.construct(carBuilder);
        var truck = shop.construct(truckBuilder);

        car.say();
        truck.say();

        log.show();
    }

    run();
</script>
</html>
